#!/usr/bin/perl -w

# This script is used to dump the all city data to a php file
# Author : RainX
use DBI;

my $sourceDir;
$sourceDir  = "D:/databases/train_ticket/orig";
my $fileName = shift;

my $dbh = DBI->connect("dbi:SQLite:dbname=/databases/train_ticket/tickets","","");

my $headerStr = qq(<?php
// For improve performance. gen a php array to store the city_name => id table
// this array is generate by dump_to_php.pl .any questions contact RainX

// ---------------------------------------------------------------------------

);
 $headerStr .= "\$cityId2Name=array(";
# $headerStr .= "\$cityName2Id=array(";
$headerStr .= allCities();
$headerStr .= "); ?>";
print $headerStr;
open (PHPFILE, ">$fileName");
print PHPFILE $headerStr;
close(PHPFILE);

$dbh->disconnect();


# fetch all cities from db
sub allCities
{
    my $statment = $dbh->prepare("select id, city_name from city");
    $statment->execute();
    my $cityName;
    my $cityId;
    my @cities;
    my $t =",";
    my $tmp="";
    while (($cityId,$cityName) = $statment->fetchrow_array())
    {
            if ($cityId == 9999)
            {
                    $t = "";
            }
            if (isExisting($cityId))
            {
                     $tmp.="'".$cityId."'=>'".$cityName."'".$t;
                     # $tmp.="'".$cityName."'=>".$cityId.$t;
            }
            # $cities[$cityId]=$cityName;
    }
    return $tmp;
}

# isExisting
sub isExisting
{
    my ($cityId) = @_;
    my $statment = $dbh->prepare("select id from price_bj where s_city_id=$cityId or e_city_id=$cityId");
    $statment->execute();
    if ($statment->fetchrow_array())
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
